
import WKSDK, { Channel, ChannelTypeGroup, ConnectStatus, Message, MessageImage, MessageText, Setting } from "wukongimjssdk";
import singleton from "../Singleton";
import LocationMsg from "./LocationMsg";
import VoiceMsg from "./VoinceMsg";

/**
 * 悟空im
 */
const imUid = ref('');//im的uid
const imToken = ref('');//im的token

/**
 * 消息类型
*/
enum WK_MSG_TYPES {
	text = 1,//文本
	image = 2,//图片
	voice = 3,//语音
	location = 6,//位置
}

enum READ_STATE {
	unread = 0,//未读
	readed = 1,
}

type initOps = {
	token : string,
	url : string,
	uid : string,
}

class WkIm {
	public channel_id = '';
	private connectStatus = ConnectStatus.Disconnect;
	// eslint-disable-next-line
	private events = new Map<string, null | ((args ?: any) => void)>();
	
	private eventWhiteList = ['msg-send', 'msg-receive'];


	public init (options : initOps) {
		if (!options.token || !options.url) {
			throw new Error('初始化悟空im参数错误');
		};
		imUid.value = options.uid;
		imToken.value = options.token;
		WKSDK.shared().config.uid = options.uid;
		WKSDK.shared().config.token = options.token;
		WKSDK.shared().config.addr = options.url;
		this.registerMessage();
		this.initCustomEventLister();
		this.initEventLister();
		WKSDK.shared().connectManager.connect();
	}

	public disconnect () {
		WKSDK.shared().connectManager.disconnect();
	}
	// eslint-disable-next-line
	public initSDK(options: any) {
		WKSDK.shared().config.uid = options.uni;
		WKSDK.shared().config.token = options.token;
	}

	//注册其他类型消息
	private registerMessage() {
		WKSDK.shared().register(WK_MSG_TYPES.location, () => new LocationMsg());
	}

	//初始化相关事件监听
	private initEventLister () {
		//监听链接状态
		WKSDK.shared().connectManager.addConnectStatusListener((status) => {
			this.connectStatus = status;
		});
		//监听收到消息
		WKSDK.shared().chatManager.addMessageListener((message) => {
			const eventName = message.send ? 'msg-send' : 'msg-receive';
			const handler = this.events.get(eventName);
			handler && handler(serverMsg2Web(message));
		});

		//监听会话状态
		// eslint-disable-next-line
		WKSDK.shared().conversationManager.addConversationListener((conversation, action) => {
			// console.log('监听会话状态', conversation, action);
		});
		//监听消息状态
		// eslint-disable-next-line
		WKSDK.shared().chatManager.addMessageStatusListener((ackPacket) => {
			// console.log('消息状态', ackPacket);
		});
	}

	//初始化自定义时间监听
	private initCustomEventLister () {
		this.eventWhiteList.forEach(() => {
			this.events.set('msg-send', null);
			this.events.set('msg-receive', null);
		});
	}

	//发送消息
	// eslint-disable-next-line
	sendMsg (e : any) : Promise<void> {
		return new Promise((r,j) => {
			if (this.connectStatus !== ConnectStatus.Connected) {
				return j({
					code : 999910,
					msg : 'im未连接或连接状态异常'
				});
			};
			const setting = new Setting();
			setting.receiptEnabled = true;
			WKSDK.shared().chatManager.send(
				webMsg2Server(e), 
				new Channel(e.channel_id, ChannelTypeGroup),
				setting
			).then(() => {
				r();
			});
		});
	}

	on (eventName : typeof this.eventWhiteList[number] , handler : () => void) {
		if (this.events.has(eventName)) {
			this.events.set(eventName, handler);
		}
	}

	off (eventName : typeof this.eventWhiteList[number]) {
		if (this.events.has(eventName)) {
			this.events.set(eventName, null);
		}
	}
};


function serverMsg2Web (message : Message) {
	return {
		from_uid : message.fromUID,
		channel_id : message.channel ? message.channel.channelID : '',
		client_msg_no : message.clientMsgNo,
		// eslint-disable-next-line
		message_idstr : message.send ? ((message as any).message_id || '') : (message.messageID || ''),
		is_my_msg : message.send,
		readed : READ_STATE.unread,
		timestamp : message.timestamp,
		payload : {
			content : message.contentType === WK_MSG_TYPES.text ? message.content.text : '未知消息',
			type : WK_MSG_TYPES.text,
			url : [WK_MSG_TYPES.image, WK_MSG_TYPES.voice].includes(message.contentType) ? message.content.url : '',
			timeTrad : [WK_MSG_TYPES.voice].includes(message.contentType) ? message.content.timeTrad : 0,
			lat : [WK_MSG_TYPES.location].includes(message.contentType) ? message.content.lat : 0,
			lng : [WK_MSG_TYPES.location].includes(message.contentType) ? message.content.lng : 0,
		}
	};
}

function webMsg2Server (customMsg) {
	let ins;
	if (customMsg.type === WK_MSG_TYPES.text) {
		ins = new MessageText(customMsg.text);
	} else if (customMsg.type === WK_MSG_TYPES.image) {
		ins = new MessageImage();
		ins.url = customMsg.url;
	} else if (customMsg.type === WK_MSG_TYPES.voice) {
		ins = new VoiceMsg();
		ins.url = customMsg.url;
		ins.timeTrad = customMsg.timeTrad;
	} else {
		ins = new MessageText('未知类型消息');
	};
	return ins;
}

const SingleAudioMgr = singleton(WkIm);
const wkim = new SingleAudioMgr();
export {
	wkim,
	WK_MSG_TYPES,
	READ_STATE,
	imUid,
	imToken
};